import {render, DirectiveBinding, h} from "vue";
import store from '@/store'
import {ElIcon} from "element-plus";
import SvgIcon from '@/components/svg-icon/index.vue'


export function hasPermission(item: string | string[], args?: string|undefined): boolean| { title: string; icon: string; [key:string]:any } {
    let it: any;
    const {buttons} = store.userStore;
    if (buttons) {
        if (Array.isArray(item)) {
            for (let data of item) {
                it = data.length > 0?buttons[data]:'none';
                if ((!args || args === 'or') && it) {
                    // 取第一个权限作为默认值返回
                    break;
                }
                if (args === 'add' && !it) {
                    // 取最后一个权限作为默认值返回
                    break;
                }
            }
        } else {
            it = item === 'none'? item:buttons[item];
        }
    }
    return it? it:false;
}
/**
 * 基于权限标识权限指令
 * 使用手册：
 * v-auth:or     值可以为字符串和数组，权限标识码匹配其一就显示组件
 * v-auth:all    值只可以是数组，权限标识码全部包含才显示组件
 * v-auth        v-auth:or 的简写
 */
export const auth = {

    mounted(el: HTMLElement, binding: DirectiveBinding) {
        const {value, arg, modifiers} = binding;
        if (value) {
            let rs = hasPermission(value, arg)
            if (arg && !['or', 'add'].includes(arg)) {
                console.error(`v-auth'${arg}'错误，v-auth 或 v-auth:or 或 v-auth:add`)
            }
            // 无权限时，从父节点中移除该节点
            if (rs === false) {
                el.remove();
            } else if (typeof rs === 'object' && arg === undefined){
                if (el.localName === 'button') {
                    if (el.children.length > 1 && el.children[0].localName === 'i') {
                        return;
                    } else {
                        el.innerHTML = '';
                        // 重新添加节点
                        render(h(ElIcon, {}, {default: ()=> h(SvgIcon, {icon: rs.icon},{})}), el);

                        if (!el.classList.contains('is-circle')) {
                            const span = document.createElement('span');
                            span.innerText = rs.title;
                            el.appendChild(span);
                        } else {
                            el.title = rs.title;
                        }
                    }
                } else if (el.localName === 'i' && el.className.indexOf('el-icon') !== -1) {
                    render(h(SvgIcon, {icon: rs.icon},{}), el);
                }
            }
        }
    },
}
